<?php
//Add by peace@warmy.cn
//当前系统如果处于调试状态，则显示所有的错误信息以及警告信息，便于调试

if(DEBUG == 1)
	error_reporting(E_ALL);
else 
	error_reporting(0);
//Initialize session data
session_start();
if(DEBUG == 1)
{
	//判断当PHP前版本是否正确

	if(PHP_VERSION < '5.1.6')
		Notify::halt("Minimum system requirements for PHP version 5.1.6","http://www.php.net/");
	if(check_mysql_library() == 0)
		$Notify->halt("System configuration is not complete, no loading MYSQL","mailto:".WEBMASTER);
	//判断数据库的版本是否正确
	$version	= check_php_version();
	if($version == "")
		Notify::halt("Connecting to the database server failure, please contact management system","mailto:".WEBMASTER);
	elseif($version < '5.0.24')
		Notify::halt("Minimum system requirements for MySQL version 5.0.24","http://www.mysql.com/");
	//判断GB库是否加载了，且需要判断其版本是正确

	$version	= check_gd_version();
	if($version == -1)
		$Notify->halt("PHP Configuration incomplete, please loading the GD library","mailto:".WEBMASTER);
	elseif($version == 0)
		$Notify->halt("GD shall not be less than the version 2.0.28","mailto:".WEBMASTER);
	unset($version);
}
//如果系统配置，没有打开magic_quotes，则需要对输入的数据进行处理

if(get_magic_quotes_gpc() == 0)
{
	if(isset($_POST))
		$_POST		= magic_convert($_POST);
	if(isset($_GET))
		$_GET		= magic_convert($_GET);
	if(isset($_COOKIE))
		$_COOKIE	= magic_convert($_COOKIE);
}
$_POST = filter_xss($_POST,ALLOWED_HTMLTAGS);
/**
 * 递归处理数据
 *
 * @param  $array
 * @return
 */
function magic_convert($array)
{
	if (is_array($array))
	{
		foreach($array as $key=>$value)
		{
			if(is_array($value))
				$array[$key]	= magic_convert($value);
			else
				$array[$key]	= addslashes($value);
		}
	}
	else
		$array	= addslashes($array);
	return $array;
}
/**
 * 判断GD的版本是否正确

 *
 * @return unknown
 */
function check_gd_version()
{
	if (function_exists('gd_info'))
	{
		$GDArray = gd_info();
		if (!$GDArray['GD Version'])
			$gd_version_number = 0;
		else
			$gd_version_number = 1;
		unset($GDArray);
	}
	else
		$gd_version_number = -1;
	return $gd_version_number;
}
/**
 * 判断MYSQL类是否加载

 *
 * @return unknown
 */
function check_mysql_library()
{
	if (function_exists('mysql_connect'))
		return 1;
	else
		return 0;
}
/**
 * 判断MYSQL 的版本是否正确

 *
 * @return unknown
 */
function check_php_version()
{
	$mysql_version	= "";
	mysql_connect(DB_HOST,DB_USER,DB_PWD);
	if(($query = mysql_query("SELECT VERSION()"))==true)
	{
		if(($row = mysql_fetch_array($query,MYSQL_NUM))==true)
		{
			$mysql_version	= $row[0];
		}
		else
			$mysql_version 	= "";
	}
	else
		$mysql_version	= "";
	return $mysql_version;
}
if(!defined('DIR_SEP')) {
    define('DIR_SEP', DIRECTORY_SEPARATOR);
}
/**
 * 自动加载类

 *
 * @param unknown_type $class_name
 */
function __autoload($class_name) {
	require_once $class_name . '.class.php';
}
/**
 * 加载缓存数据
 *
 * @param unknown_type $file			缓存文件名

 * @param unknown_type $path			缓存路径
 * @param unknown_type $iscachevar		
 * @return unknown
 */
function cache_read($file, $path = '', $iscachevar = 0)
{
	//组合缓存文件路径名

	if(!$path) $path = CACHE_PATH;
	$cachefile = $path.$file;
	if($iscachevar)
	{
		global $TEMP;
		$key = 'cache_'.substr($file, 0, -4);
		return isset($TEMP[$key]) ? $TEMP[$key] : $TEMP[$key] = @include($cachefile);
	}
	return @include $cachefile;
}


/**
 * 写缓存文件

 *
 * @param unknown_type $file		缓存文件名

 * @param unknown_type $array		待写缓存的数据，一般是数组
 * @param unknown_type $path		缓存存放路径
 * @return unknown
 */
function cache_write($file, $array, $path = '')
{
	if(!is_array($array)) return false;
	$array = "<?php\nreturn ".var_export($array, true).";\n?>";
	//组合缓存文件路径文件
	$cachefile = ($path ? $path : CACHE_PATH).$file;
	//写入缓存文件
	$strlen = file_put_contents($cachefile, $array);
	//修改缓存文件权限
	@chmod($cachefile, 0777);
	//返回写入字节数

	return $strlen;
}
/**
 * 删除缓存文件
 *
 * @param unknown_type $file
 * @param unknown_type $path
 * @return unknown
 */
function cache_delete($file, $path = '')
{
	$cachefile = ($path ? $path : CACHE_PATH).$file;
	return @unlink($cachefile);
}
function set_cookie($var, $value = '', $time = 0)
{
	$time = $time > 0 ? $time : ($value == '' ? TIME - 3600 : 0);
	$s = $_SERVER['SERVER_PORT'] == '443' ? 1 : 0;
	$var = COOKIE_PRE.$var;
	$_COOKIE[$var] = $value;
	if(is_array($value))
	{
		foreach($value as $k=>$v)
		{
			setcookie($var.'['.$k.']', $v, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);
		}
	}
	else
	{
		setcookie($var, $value, $time, COOKIE_PATH, COOKIE_DOMAIN, $s);
	}
}


/**
 * 返回COOKIE的值

 *
 * @param unknown_type $var
 * @return unknown
 */
function get_cookie($var)
{
	$var = COOKIE_PRE.$var;
	return isset($_COOKIE[$var]) ? $_COOKIE[$var] : false;
}
function wcms_auth($txt, $operation = 'ENCODE', $key)
{
	$txt	= $operation == 'ENCODE' ? $txt : base64_decode($txt);
	$len	= strlen($key);
	$code	= '';
	for($i=0; $i<strlen($txt); $i++){
		$k		= $i % $len;
		$code  .= $txt[$i] ^ $key[$k];
	}
	$code = $operation == 'DECODE' ? $code : base64_encode($code);
	return $code;
}

/**
 * 文件下载，可以指定另存时的文件名，默认为原来的文件名
 *
 * @param unknown_type $filepath
 * @param unknown_type $filename
 */
function file_down($filepath, $filename = '')
{
	if(!$filename) $filename = basename($filepath);
	if(is_ie()) $filename = rawurlencode($filename);
	$filetype = fileext($filename);
	$filesize = sprintf("%u", filesize($filepath));
	if(ob_get_length() !== false) @ob_end_clean();
	header('Pragma: public');
	header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
	header('Cache-Control: no-store, no-cache, must-revalidate');
	header('Cache-Control: pre-check=0, post-check=0, max-age=0');
	header('Content-Transfer-Encoding: binary');
	header('Content-Encoding: none');
	header('Content-type: '.$filetype);
	header('Content-Disposition: attachment; filename="'.$filename.'"');
	header('Content-length: '.$filesize);
	readfile($filepath);
	exit;
}
/**
 * 判断当前客户浏览器是否是IE
 *
 * @return unknown
 */
function is_ie()
{
	$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
	if((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false)) return false;
	if(strpos($useragent, 'msie ') !== false) return true;
	return false;
}

/**
 * 获取文件的扩展名称

 *
 * @param unknown_type $filename
 * @return unknown
 */
function fileext($filename)
{
	return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}

/**
 * 过滤提交的信息中包含其它禁止的标签及函数
 */
function filter_xss($string, $allowedtags = '', $disabledattributes = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavaible', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragdrop', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterupdate', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmoveout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload'))
{
	if(is_array($string))
	{
		foreach($string as $key => $val) $string[$key] = filter_xss($val, $allowedtags);
	}
	else
	{
		$string = strip_tags($string, $allowedtags) ;
		$string = preg_replace('/<(.*?)>/ie', "'<'.preg_replace(array('/javascript:[^\"\']*/i', '/(".implode('|', $disabledattributes).")[ \\t\\n]*=[ \\t\\n]*[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", $string);

		$string = preg_replace('/\s('.implode('|', $disabledattributes).').*?([\s\>])/', '\\2', $string);
	}
	return $string;
}
/**
 * 删除所有管理员的

 * Author				peace@warmy.cn
 * Create Date			2009-03-12
 * 当管理功能名称、显示顺序、权限发生了变化，以及权限组发生了变化，都需要删除管理员的缓存

 */
function cache_delete_manage()
{
	//获取管理员缓存下的所有文件

	$path = DOCUMENTROOT."/cache/admin";
	$dh  = opendir($path);
	$path = "{$path}/";
	while (false !== ($filename = readdir($dh))) {
	    if(is_file("{$path}/{$filename}"))
	    {
	    	cache_delete($filename,$path);
	    }
	}

}
/**
 * 返回客户端IP
 *
 * @return unknown
 */
function ip()
{
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown'))
	{
		$ip = getenv('HTTP_CLIENT_IP');
	}
	elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown'))
	{
		$ip = getenv('HTTP_X_FORWARDED_FOR');
	}
	elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown'))
	{
		$ip = getenv('REMOTE_ADDR');
	}
	elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown'))
	{
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	$matches = array();
	return preg_match("/[\\d\\.]{7,15}/", $ip, $matches) ? $matches[0] : 'unknown';
}

/**
 * 返回GET方式提交的数字变量

 *
 * @param unknown_type $key		变量名称
 * @return unknown				数字
 */
function GETD($key)
{
	return (isset($_GET[$key]) && ereg("^[0-9]+$",$_GET[$key])) ? $_GET[$key] : 0;
}
/**
 * 返回POST方式提交的数字变量

 *
 * @param unknown_type $key		变量名称
 * @return unknown				数字
 */
function POSTD($key)
{
	return (isset($_POST[$key]) && ereg("^[0-9]+$",$_POST[$key])) ? $_POST[$key] : 0;
}

function CheckDomain()
{
	if(isset($_SERVER['HTTP_REFERER']) && $_SERVER['HTTP_REFERER'] != '')
	{
		$url  = $_SERVER['HTTP_REFERER'];
		$pattern = "http://(.[^/\\]*)";
		if(ereg($pattern,$url,$arr))
		{
			if(isset($arr[1]) && $arr[1]!='' && strtolower($arr[1]) == (strtolower($_SERVER['SERVER_NAME']).(isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT']!='' && $_SERVER['SERVER_PORT']!='80'?":{$_SERVER['SERVER_PORT']}":'')))
				return true;
			else 
				return false;
		}
		else 
			return false;
	}
	return false;
}
function POSTS($key)
{
	return isset($_POST[$key]) ? $_POST[$key] : '';
}
function GETS($key)
{
	return isset($_GET[$key]) ? $_GET[$key] : '';
}

function back($param = '')
{
	$back = strtolower(basename($_SERVER['HTTP_REFERER']));
	if(strpos($back,"?") > 0)
		$back = substr($back,0,strpos($back,"?"));
	$self = strtolower(trim(basename($_SERVER['SCRIPT_NAME']),'/'));	
	$path = dirname($_SERVER['SCRIPT_NAME']);
	if($back!=$self) 
	{
		$path = strlen($path) == 1 ? '': $path . '/';
		$back = "{$path}$self";
		if($param != '') $back = "$back?$param";
	}
	else 
		$back = "Javascript:window.history.go(-1)";

	return $back;
}

function about($max){
	$about = GETD('about');
	if($about < 0 || $about > $max) $about = 0;
	$GLOBALS['smarty']->assign('about',$about);
	return  $about;
}
?>